package com.sixbro.orm.jpa.api;

import com.alibaba.fastjson.JSON;
import com.sixbro.orm.jpa.entity.User;
import com.sixbro.orm.jpa.factory.SpecificationFactory;
import com.sixbro.orm.jpa.repository.UserRepository;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.persistence.criteria.Predicate;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>
 *  首先原因是pageable这个插件中默认的page是从0开始读的和我们之前用的pageHelper的page默认初始值是不一样的
 * </p>
 *
 * @author: Mr.Lu
 * @since: 2021/12/10 21:22
 */
@RestController
public class IndexController {

    private final UserRepository userRepository;

    public IndexController(UserRepository userRepository) {
        this.userRepository = userRepository;
    }

    @GetMapping("/")
    public ResponseEntity list(
            @RequestParam(value = "page", defaultValue = "1", required = false) Integer page,
            @RequestParam(value = "limit", defaultValue = "10", required = false) Integer limit,
            @RequestParam(value = "nickname",required = false) String nickname,
            @RequestParam(value = "username",required = false) String username,
            @RequestParam(value = "telephone",required = false) String telephone,
            @RequestParam(value = "version",required = false) String version,
            @RequestParam(value = "createTime",required = false) Date createTime,
            @RequestParam(value = "city",required = false) String city
    ){

        // 具体实现类中 获取到page后
        // pageable默认是从0开始的 page如果为null或者小于0,则page为0，否则-1
        page = page == null || page < 0 ? 0: page - 1;

//        Sort sort = Sort.by(Sort.Direction.DESC, "id");
//        PageRequest pageRequest = PageRequest.of(page, limit,sort);

        // 构造条件
        Specification<User> specification = (root, query, builder) -> {
            List<Predicate> predicates = new ArrayList<>();
            if (StringUtils.isNoneBlank(nickname)) {
                // liked的查询条件
                predicates.add(builder.like(root.get("username").as(String.class), "%" + nickname + "%"));
            }
            if (StringUtils.isNoneBlank(telephone)) {
                // equal查询条件
                predicates.add(builder.equal(root.get("phone").as(String.class), telephone));
            }
            if (StringUtils.isNoneBlank(version)){
                // greaterThan大于等于查询条件
                predicates.add(builder.greaterThan(root.get("version").as(String.class), version));
            }
            if (createTime != null){
                //根据时间区间去查询
                predicates.add(builder.between(root.get("createTime"), createTime, createTime));
            }
            if (StringUtils.isNotBlank(city)) {
                //联表查询，利用root的join方法，根据关联关系表里面的字段进行查询。
                predicates.add(builder.equal(root.join("receivingAddresses").get("city"), city));
                //predicates.add(cb.equal(root.get("receivingAddresses").get("city"), city));
            }
            return query.where(predicates.toArray(new Predicate[predicates.size()])).getRestriction();
        };
        Page<User> users = userRepository.findAll(specification, PageRequest.of(page, limit, Sort.by("id").descending()));
        List<User> content = users.getContent();
        System.err.println(JSON.toJSONString(content));
        return ResponseEntity.ok().body(users);
    }

    @GetMapping("/factory")
    public ResponseEntity factory(
            @RequestParam(value = "page", defaultValue = "1", required = false) Integer page,
            @RequestParam(value = "limit", defaultValue = "10", required = false) Integer limit,
            @RequestParam(value = "nickname",required = false) String nickname,
            @RequestParam(value = "username",required = false) String username,
            @RequestParam(value = "telephone",required = false) String telephone,
            @RequestParam(value = "version",required = false) String version,
            @RequestParam(value = "createTime",required = false) Date createTime,
            @RequestParam(value = "city",required = false) String city
    ){

        // 具体实现类中 获取到page后
        // pageable默认是从0开始的 page如果为null或者小于0,则page为0，否则-1
        page = page == null || page < 0 ? 0: page - 1;

//        Sort sort = Sort.by(Sort.Direction.DESC, "id");
//        PageRequest pageRequest = PageRequest.of(page, limit,sort);

        // 构造条件
        Specification<User> specification = SpecificationFactory.likeLeft("name", "o")
                .and(SpecificationFactory.likeRight("uname", "o"))
                .and(SpecificationFactory.isNull("email"));

        Page<User> users = userRepository.findAll(specification, PageRequest.of(page, limit, Sort.by("id").descending()));
        System.err.println(JSON.toJSONString(users.getContent()));
        return ResponseEntity.ok().body(users);
    }
}
